import React,{PureComponent} from 'react';
import { Form, Button,Modal,Select,Row,Col, Divider, Cascader, Card,Checkbox,Icon,Input} from 'antd';
import { routerRedux } from 'dva/router';
import AddAttr from '../../../components/goods/goodsManage/addAttr/AddAttr';
import styles from './goodsManage.less';
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const {Option}=Select;
let uuid = 0;

import reactCSS from 'reactcss'
import SketchPicker  from 'react-color';

export default class GoodsGI extends React.Component {
    state = {
        loading: false,
        goodsType: [],
        attrVal: [],
        keys: [0],
        modalVisible:false,
        clickId:'',
        isChooes:false,
        displayColorPickerArr:{},
        colorArr:{},
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsType/queryAll' ,
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        goodsType: response.resultData.goodsTypeList
                    })
                }
            }
        });
    }
    handleSelect=(e)=>{
        this.props.dispatch({
            type: 'goodsType/queryAll' ,
            payload:{attr_group:e},
            callback: (response) => {
            if (response.result === 0) {
                this.setState({
                    goodsType: response.resultData.goodsTypeList
                })
            }
        }
        })
    }
    onPrev = () => {
        const {dispatch} = this.props;
        dispatch(routerRedux.push('/goods/addGoods/goodsSI'));
    };
    onValidateForm = (e) => {
        const {dispatch} = this.props;
        //将颜色加入到map中
        const submitColorMap=new Map()
        const colorArrNow=this.state.colorArr
        for (var key in colorArrNow){
            const rgba=[]
            rgba.push(colorArrNow[key].r,colorArrNow[key].g,colorArrNow[key].b,colorArrNow[key].a)
            submitColorMap.set(key,rgba);
        }

        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                //返回该商品所有属性的id
                const attrId=this.state.attrVal.map((key,index)=>{
                    return (key.attr_id)
                })
                const param={
                    ...values,
                    attrId:attrId,
                    color:submitColorMap
                }
                console.log("param",param)
                dispatch({
                    type: 'goodsManage/keepData',
                    payload: {
                        ...param,
                    },
                });
                dispatch(routerRedux.push('/goods/addGoods/goodsOI'));
            }
        });
    }

    submitForm = (e) => {
        const {dispatch, data} = this.props;
        this.props.form.validateFieldsAndScroll((err, values) => {
           console.log("submitValue",values)
        });
    }

    stepSubmit = (e) => {
        const {dispatch, data} = this.props;
        const submitColorMap=new Map()
        const colorArrNow=this.state.colorArr
        for (var key in colorArrNow){
            const rgba=[]
            rgba.push(colorArrNow[key].r,colorArrNow[key].g,colorArrNow[key].b,colorArrNow[key].a)
            submitColorMap.set(key,rgba);
        }

        this.props.form.validateFieldsAndScroll((err, values) => {
            console.log("values",values)
            console.log("====")
            if (!err) {
                //返回该商品所有属性的id
                const attrId=this.state.attrVal.map((key,index)=>{
                    return (key.attr_id)
                })
                const param={
                    ...values,
                    attrId:attrId,
                    color:submitColorMap
                }
                console.log("param",param)

                let user_id = '';
                const userInfoState = sessionStorage.getItem("userInfoState");
                if (userInfoState !== null) {
                    const {userInfo} = JSON.parse(userInfoState);
                    user_id = userInfo.user_id;
                }
                dispatch({
                    type: 'goodsManage/keepData',
                    payload: {
                        ...param,
                    },
                    callback: (response) => {
                        if (response){
                            const editType = data.editType;
                            this.props.goodsAttrSubmit(editType,user_id,param);
                        }
                    }
                });
            }
        });
    }

    getAttr = (value) => {
        this.setState({
            attrVal:[],
            displayColorPickerArr:{},
            colorArr:{},
        })
        if (value.length > 0) {
            const cat_id = value[0];
            const {dispatch} = this.props;
            dispatch({
                type: 'attribute/queryAll',
                payload: {
                    cat_id:cat_id
                },
                callback: (response) => {
                    if (response.result === 0){
                        const attrValues=response.resultData.attrList.map((value,index)=>{
                            const attr=value.attrVal.map((key,index)=>{
                                return {value:key.label,label:key.label};
                            })
                            value.attrVal=attr;
                            return value;
                        })
                        this.setState({
                            attrVal: attrValues
                        })

                        //初始化可视化数组
                        const disMap=[]
                        response.resultData.attrList.map((key,index)=>{
                            const disId="displayColorPickerArr"+key.attr_id
                            disMap[disId]=false
                        })
                        this.setState({
                            displayColorPickerArr: disMap
                        })
                        //初始化颜色数组
                        const colorMap=[]
                        response.resultData.attrList.map((key,index)=>{
                            const colorId="color"+key.attr_id
                            colorMap[colorId]={
                                r: '241',
                                g: '112',
                                b: '19',
                                a: '1',
                            }
                        })
                        this.setState({
                            colorArr: colorMap
                        })

                    }
                }
            });
        }
        this.setState({
            isChooes:true
        })
    }

    handleCheckBox=(checkValues)=>{
       // console.log("checkValues",checkValues)
    }
    handleModalVisible=(flag)=>{
        this.setState({
            modalVisible:!!flag,
        })
        //console.log(this.state.attrVal)
    }
    handleClick=(flag,id)=>{
        this.handleModalVisible(flag);
        this.setState({
            clickId:id,
        })
    }
    //点击对应的自定义按钮，为对应的属性赋值
    handleSubmit=(attrList,clickId)=>{
       const {attrVal}=this.state;
       const values= attrVal.map((key,index)=>{
           if(key.attr_id===clickId){
               key.attrVal=attrList;
           }
            return key;
        })
        this.setState({
            attrVal:values,
        })

    }

    //显示多个颜色选择板
    handleColorClickArr = (attr_id) => {
        console.log(111)
        this.state.displayColorPickerArr["displayColorPickerArr"+attr_id]=!this.state.displayColorPickerArr["displayColorPickerArr"+attr_id]
        const nowDisplayColorPickerArr=this.state.displayColorPickerArr
        this.setState({
            displayColorPickerArr:nowDisplayColorPickerArr
        })
    };

    handleColorCloseArr = (attr_id) => {
        console.log(222)
        this.state.displayColorPickerArr["displayColorPickerArr"+attr_id]=false
        const nowDisplayColorPickerArr=this.state.displayColorPickerArr
        this.setState({
            displayColorPickerArr:nowDisplayColorPickerArr
        })
    };

    handleColorChangeArr = (attr_id,color) => {
        console.log(333+":attr_id"+attr_id+"color:",color.rgb)
        this.state.colorArr["color"+attr_id]=color.rgb;
        const nowColorArr=this.state.colorArr
        this.setState({
            colorArr:nowColorArr
        })
    };

    render() {
        //动态颜色css
        let colorStyleArr={}
        if (this.state.isChooes) {
            if (JSON.stringify(this.state.colorArr) !== "{}") {
                this.state.attrVal.map((value, index) => {
                    const colorName = "colorStyle" + value.attr_id
                    colorStyleArr[colorName] = reactCSS({
                        'default': {
                            color: {
                                top:'10px',
                                width: '36px',
                                height: '14px',
                                borderRadius: '2px',
                                background: `rgba(${ this.state.colorArr["color"+value.attr_id].r }, ${ this.state.colorArr["color"+value.attr_id].g }, ${ this.state.colorArr["color"+value.attr_id].b }, ${ this.state.colorArr["color"+value.attr_id].a })`,
                            },
                            swatch: {
                                marginLeft:'5px',
                                padding: '4px',
                                background: '#fff',
                                borderRadius: '1px',
                                boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
                                display: 'inline-block',
                                cursor: 'pointer',
                            },
                            popover: {
                                position: 'absolute',
                                zIndex: '2',
                            },
                            cover: {
                                position: 'fixed',
                                top: '0px',
                                right: '0px',
                                bottom: '0px',
                                left: '0px',
                            },
                        },
                    });
                })
            }
        }

        const { formItemLayout, data, dispatch, submitting} = this.props;
        const {attrVal,modalVisible,clickId}=this.state;
        const {getFieldDecorator, getFieldValue} = this.props.form;
        let goodsType = data.editType === 'add' ? [] : eval("["+data.goods_type+"]");
        const isDisplay=data.editType==='add'?true:false;
        //动态复选框
        const checkBoxGroup=attrVal.map((value,index)=>{
          //  console.log("value.attrVal",value.attrVal)
            return (
                <FormItem
                    {...formItemLayout}
                 label={value.attr_name}>
                    {getFieldDecorator(
                        `${value.attr_id}`
                    )(
                        value.attr_input_type===0?(value.attrVal.length!==0?<CheckboxGroup options={value.attrVal} onChange={this.handleCheckBox}/>:<Button type="primary" size="small" onClick={()=>this.handleClick(true,value.attr_id)}>自定义</Button>):
                            <CheckboxGroup options={value.attrVal} onChange={this.handleCheckBox}>
                            </CheckboxGroup>
                    )}
                </FormItem>
            )
        });
        //动态颜色选择器
        const colorPicks = JSON.stringify(colorStyleArr)==='{}' ?  <div></div> :
            attrVal.map((value,index)=>{
                return(

                    <div style={{ margin: '15px 85px', fontSize:'14px'}}><span>{value.attr_name}</span>:
                    <div style={ colorStyleArr["colorStyle" + value.attr_id].swatch } onClick={ ()=>this.handleColorClickArr(value.attr_id) }>
                        <div style={ colorStyleArr["colorStyle" + value.attr_id].color } />
                    </div>
                    { this.state.displayColorPickerArr["displayColorPickerArr"+value.attr_id] ? <div style={ colorStyleArr["colorStyle" + value.attr_id].popover }>
                        <div style={ colorStyleArr["colorStyle" + value.attr_id].cover } onClick={ ()=>this.handleColorCloseArr(value.attr_id) }/>
                        <SketchPicker color={ this.state.colorArr["color"+value.attr_id] } onChange={ (color)=>this.handleColorChangeArr(value.attr_id,color) } />
                    </div> : null }
                </div>

                    )
            })

        return(
            <Card title="属性信息" bordered={false}>
                <Form layout="horizontal" className={styles.stepForm}>
                    <FormItem
                        {...formItemLayout}
                        label={<span>属性分类</span>}
                    >
                        {getFieldDecorator('attr_group',{
                            initialValue:''
                        })(
                            <Select placeholder="请选择" onChange={this.handleSelect} style={{width: '100%'}} >
                                <Option value="">请选择</Option>
                                <Option value="pro_param">参数</Option>
                                <Option value="pro_attr">属性</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={<span>商品所属类型</span>}
                    >
                        {getFieldDecorator('goods_type', {
                            initialValue: goodsType || [],
                            rules: [{
                                type: 'array',
                                required: true, message: '请选择商品类型',
                            }],
                        })(
                            <Cascader changeOnSelect options={this.state.goodsType} onChange={this.getAttr}/>
                        )}
                    </FormItem>
                    <Divider style={{ margin: '24px 0' }} >商品规格</Divider>
                    {checkBoxGroup}
                    <Divider style={{ margin: '24px 0' }} >颜色选择</Divider>
                    {colorPicks}
                    <Divider style={{ margin: '24px 0' }} />
                    <Form.Item
                        style={{ marginBottom: 8 }}
                        wrapperCol={{
                            xs: { span: 24, offset: 0 },
                            sm: { span: formItemLayout.wrapperCol.span, offset: formItemLayout.labelCol.span },
                        }}
                        label=""
                    >
                        <Button onClick={this.onPrev}>
                            上一步
                        </Button>
                        <Button type="primary" onClick={this.onValidateForm} loading={submitting}  style={{ marginLeft: 8 }}>
                            下一步
                        </Button>
                        <Button  type="default" onClick={this.stepSubmit} disabled={isDisplay} style={{ marginLeft: 8 }}>
                            保存
                        </Button>
                    </Form.Item>
                </Form>
                <Modal
                    visible={modalVisible}
                    title="手工录入属性"
                    footer={null}
                    onCancel={()=>this.handleModalVisible(false)}
                >
                    <AddAttr
                        handleCancel={()=>this.handleModalVisible(false)}
                        handleSubmit={this.handleSubmit}
                        clickId={clickId}/>
                </Modal>
            </Card>
        )
    }
}

